package com.woniuxy.joylifeshop.configuration;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * 用于向浏览器发送消息
 */
public class ChatUtil {
	//保存所有客户端的session
	public static Map<String, Session> messageMap = new ConcurrentHashMap<>();

	//向指定的客户端发送消息
	public static void sendMessage(Session session,String message) {
		if (session!=null) {
			RemoteEndpoint.Basic basic = session.getBasicRemote();//发送消息的对象
			if (basic!=null) {
				try {
					basic.sendText(message);	//发送消息
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	//向所有人发送消息
	//循环map 调用sendMessage方法
	public static void sendAll(String message) {
		Iterator<String> iterator = messageMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			Session session = messageMap.get(key);
			sendMessage(session, message);
		}
	}

}
